<template>
  <div class="config-management">
    <!-- 搜索卡片 -->
    <div class="search-section">
      <el-card shadow="hover" class="search-card">
        <template #header>
          <div class="search-header">
            <div class="search-title">
              <el-icon><Search /></el-icon>
              <span>搜索与筛选</span>
            </div>
          </div>
        </template>
        
        <el-form :model="searchForm" class="search-form">
          <div class="search-form-content">
            <div class="search-form-fields">
              <el-form-item label="是否监控">
                <el-select v-model="searchForm.is_monitor" placeholder="选择监控状态" clearable style="width: 160px">
                  <el-option label="全部" value="" />
                  <el-option label="启用" :value="1" />
                  <el-option label="禁用" :value="0" />
                </el-select>
              </el-form-item>
              
              <el-form-item label="是否告警">
                <el-select v-model="searchForm.is_alert" placeholder="选择告警状态" clearable style="width: 160px">
                  <el-option label="全部" value="" />
                  <el-option label="启用" :value="1" />
                  <el-option label="禁用" :value="0" />
                </el-select>
              </el-form-item>
              
              <el-form-item label="状态">
                <el-select v-model="searchForm.status" placeholder="选择状态" clearable style="width: 160px">
                  <el-option label="全部" value="" />
                  <el-option label="仅监控" value="running" />
                  <el-option label="已停止" value="stopped" />
                  <el-option label="启用告警" value="enAlert" />
                  <el-option label="禁用告警" value="disAlert" />
                  <el-option label="全部启用" value="enAll" />
                  <el-option label="全部禁用" value="disAll" />
                </el-select>
              </el-form-item>
            </div>
            
            <div class="search-form-actions">
              <el-button 
                type="info" 
                @click="advancedSearchExpanded = !advancedSearchExpanded" 
                class="advanced-btn"
                plain
              >
                <el-icon>
                  <component :is="advancedSearchExpanded ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
                高级筛选
              </el-button>
              <el-button type="primary" @click="handleSearch" class="search-btn">
                <el-icon><Search /></el-icon>
                搜索
              </el-button>
              <el-button type="warning" @click="handleReset" class="reset-btn">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
              <el-button type="success" @click="handleCreate">
                <el-icon><Plus /></el-icon>
                新增配置
              </el-button>
            </div>
          </div>
          
          <!-- 高级筛选折叠区域 -->
          <transition name="advanced-filter">
            <div v-show="advancedSearchExpanded" class="advanced-filter-section">
              <div class="advanced-filter-fields">
                <el-form-item label="集群标识">
                  <el-select v-model="searchForm.cluster_tag" placeholder="选择集群" clearable style="width: 160px">
                    <el-option label="全部" value="" />
                    <el-option
                      v-for="tag in clusterTags"
                      :key="tag.cluster_tag"
                      :label="`${tag.cluster_tag} (${tag.count})`"
                      :value="tag.cluster_tag"
                    />
                  </el-select>
                </el-form-item>
                
                <el-form-item label="配置名称">
                  <el-input v-model="searchForm.config_name" placeholder="请输入配置名称" clearable style="width: 200px" />
                </el-form-item>
              </div>
            </div>
          </transition>
        </el-form>
      </el-card>
    </div>

    <!-- 表格卡片 -->
    <div class="table-section">
      <el-card shadow="hover" class="table-card">
        <template #header>
          <div class="table-header">
            <div class="table-title">
              <el-icon><List /></el-icon>
              <span>配置列表</span>
            </div>
            <div class="table-header-actions">
              <el-button type="success" @click="handleRefresh" class="refresh-btn" :loading="loading" size="small">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
              <div class="table-info">
                <div class="pagination-control-wrapper clickable" @click="togglePagination">
                  <span class="page-count">本页 {{ configs.length }} 条</span>
                  <div class="divider"></div>
                  <span class="pagination-info">
                    {{ currentPage }}/{{ Math.ceil(total / pageSize) || 1 }}
                  </span>
                  <el-icon class="pagination-toggle-icon">
                    <ArrowUp v-if="paginationVisible" />
                    <ArrowDown v-else />
                  </el-icon>
                </div>
              </div>
            </div>
          </div>
        </template>
        <div class="table-container">
          <el-table
            :data="configs"
            v-loading="loading"
            class="enhanced-table"
            style="width: 100%"
            :height="600"
            table-layout="fixed"
            :stripe="false"
            :border="false"
          >
            <el-table-column prop="cluster_tag" label="集群标识" width="120" fixed="left">
              <template #default="{ row }">
                <el-tag :type="getClusterTagType(row.cluster_tag)">{{ row.cluster_tag }}</el-tag>
              </template>
            </el-table-column>
            
            <el-table-column prop="config_name" label="配置名称" width="180" show-overflow-tooltip />
            
            <el-table-column prop="config_desc" label="配置描述" width="200" show-overflow-tooltip>
              <template #default="{ row }">
                <span>{{ row.config_desc || '-' }}</span>
              </template>
            </el-table-column>
            
            <el-table-column prop="fe_master_node" label="FE主节点" width="140" show-overflow-tooltip />
            
            <el-table-column prop="fe_slave_nodes" label="FE从节点" width="180" show-overflow-tooltip>
              <template #default="{ row }">
                <el-tooltip :content="row.fe_slave_nodes || '无'" placement="top">
                  <span>{{ getFeSlaveNodesCount(row.fe_slave_nodes) }}</span>
                </el-tooltip>
              </template>
            </el-table-column>
            
            <el-table-column prop="be_nodes" label="BE节点" width="200" show-overflow-tooltip>
              <template #default="{ row }">
                <el-tooltip :content="row.be_nodes" placement="top">
                  <span>{{ getBeNodesCount(row.be_nodes) }}个节点</span>
                </el-tooltip>
              </template>
            </el-table-column>
            
            <el-table-column prop="metrics_port" label="监控端口" width="100" />
            
            <el-table-column prop="is_monitor" label="监控开关" width="100" align="center">
              <template #default="{ row }">
                <el-switch
                  :model-value="row.is_monitor"
                  :active-value="1"
                  :inactive-value="0"
                  @change="(val) => handleToggleMonitor(row, val)"
                  :loading="row._monitorLoading"
                />
              </template>
            </el-table-column>
            
            <el-table-column prop="is_alert" label="告警开关" width="100" align="center">
              <template #default="{ row }">
                <el-switch
                  :model-value="row.is_alert"
                  :active-value="1"
                  :inactive-value="0"
                  @change="(val) => handleToggleAlert(row, val)"
                  :loading="row._alertLoading"
                  :disabled="row.is_monitor === 0"
                />
              </template>
            </el-table-column>
            
            <el-table-column prop="is_restart" label="自动重启" width="100" align="center">
              <template #default="{ row }">
                <el-switch
                  :model-value="row.is_restart"
                  :active-value="1"
                  :inactive-value="0"
                  @change="(val) => handleToggleRestart(row, val)"
                  :loading="row._restartLoading"
                  :disabled="row.is_monitor === 0"
                />
              </template>
            </el-table-column>
            
            <el-table-column prop="status" label="状态" width="120">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.status)" size="small">
                  {{ getStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            
            <el-table-column prop="updated_at" label="更新时间" width="180" show-overflow-tooltip />
            
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="{ row }">
                <div class="action-buttons">
                  <el-tooltip content="查看详情" placement="top">
                    <el-button type="info" size="small" @click="handleViewDetail(row)" circle>
                      <el-icon><View /></el-icon>
                    </el-button>
                  </el-tooltip>
                  <el-tooltip content="编辑配置" placement="top">
                    <el-button type="primary" size="small" @click="handleEdit(row)" circle>
                      <el-icon><Edit /></el-icon>
                    </el-button>
                  </el-tooltip>
                  <el-tooltip content="删除配置" placement="top">
                    <el-button type="danger" size="small" @click="handleDelete(row)" circle>
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </el-tooltip>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <!-- 分页折叠区域 -->
        <transition name="pagination-slide">
          <div v-show="paginationVisible" class="pagination-section">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :total="total"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handlePageChange"
              background
            />
          </div>
        </transition>
      </el-card>
    </div>

    <!-- 配置编辑对话框 -->
    <ConfigEditDialog
      v-model="dialogVisible"
      :config="currentConfig"
      :is-edit="isEdit"
      @success="handleDialogSuccess"
    />

    <!-- 配置详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      width="900px"
      :close-on-click-modal="false"
      class="unified-dialog"
    >
      <template #header>
        <DialogHeader 
          icon="View"
          title="配置详情"
          :description="currentDetail?.config_name"
          type="info"
        />
      </template>
      
      <div v-if="currentDetail" class="dialog-content">
        <!-- 基础信息 -->
        <el-descriptions title="基础信息" :column="2" border size="default">
          <el-descriptions-item label="集群标识">
            <el-tag :type="getClusterTagType(currentDetail.cluster_tag)">{{ currentDetail.cluster_tag }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="配置名称">
            {{ currentDetail.config_name }}
          </el-descriptions-item>
          <el-descriptions-item label="配置描述" :span="2">
            {{ currentDetail.config_desc || '-' }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 节点配置 -->
        <el-descriptions title="节点配置" :column="2" border size="default" style="margin-top: 20px">
          <el-descriptions-item label="FE主节点">
            {{ currentDetail.fe_master_node }}
          </el-descriptions-item>
          <el-descriptions-item label="FE从节点">
            {{ currentDetail.fe_slave_nodes || '无' }}
          </el-descriptions-item>
          <el-descriptions-item label="BE节点列表" :span="2">
            {{ currentDetail.be_nodes }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 端口配置 -->
        <el-descriptions title="端口配置" :column="3" border size="default" style="margin-top: 20px">
          <el-descriptions-item label="监控端口">
            {{ currentDetail.metrics_port }}
          </el-descriptions-item>
          <el-descriptions-item label="FE HTTP端口">
            {{ currentDetail.fe_http_port }}
          </el-descriptions-item>
          <el-descriptions-item label="BE HTTP端口">
            {{ currentDetail.be_http_port }}
          </el-descriptions-item>
          <el-descriptions-item label="FE日志端口">
            {{ currentDetail.fe_log_port || '-' }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- StarRocks配置 -->
        <el-descriptions title="StarRocks配置" :column="2" border size="default" style="margin-top: 20px">
          <el-descriptions-item label="安装目录">
            {{ currentDetail.starrocks_home || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="控制脚本">
            {{ currentDetail.control_script || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="运行用户">
            {{ currentDetail.starrocks_user || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="FE日志目录">
            {{ currentDetail.fe_log_dir || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="BE日志目录">
            {{ currentDetail.be_log_dir || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="日志保留天数">
            {{ currentDetail.log_keep_days || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="日志备份天数">
            {{ currentDetail.log_backup_days || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="日志备份目录">
            {{ currentDetail.log_backup_dir || '-' }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- Prometheus配置 -->
        <el-descriptions title="Prometheus配置" :column="1" border size="default" style="margin-top: 20px">
          <el-descriptions-item label="启用Prometheus">
            <el-tag :type="currentDetail.enable_prometheus ? 'success' : 'info'" size="small">
              {{ currentDetail.enable_prometheus ? '已启用' : '已禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="Prometheus地址">
            {{ currentDetail.prometheus_url || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="FE查询语句">
            {{ currentDetail.fe_query || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="BE查询语句">
            {{ currentDetail.be_query || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="Prometheus必需">
            <el-tag :type="currentDetail.prometheus_required ? 'warning' : 'info'" size="small">
              {{ currentDetail.prometheus_required ? '必需' : '可选' }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>

        <!-- 告警与重启配置 -->
        <el-descriptions title="告警与重启配置" :column="2" border size="default" style="margin-top: 20px">
          <el-descriptions-item label="告警Webhook">
            {{ currentDetail.webhook_url || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="告警间隔(秒)">
            {{ currentDetail.alert_interval || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="告警次数阈值">
            {{ currentDetail.max_alert_count || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="重启超时(秒)">
            {{ currentDetail.restart_timeout || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="最大重启次数">
            {{ currentDetail.max_restart_count || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="SSH用户">
            {{ currentDetail.ssh_user || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="SSH超时(秒)">
            {{ currentDetail.ssh_timeout || '-' }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 开关与状态 -->
        <el-descriptions title="开关与状态" :column="2" border size="default" style="margin-top: 20px">
          <el-descriptions-item label="监控开关">
            <el-tag :type="currentDetail.is_monitor ? 'success' : 'info'" size="small">
              {{ currentDetail.is_monitor ? '已启用' : '已禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="告警开关">
            <el-tag :type="currentDetail.is_alert ? 'success' : 'info'" size="small">
              {{ currentDetail.is_alert ? '已启用' : '已禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="自动重启">
            <el-tag :type="currentDetail.is_restart ? 'success' : 'info'" size="small">
              {{ currentDetail.is_restart ? '已启用' : '已禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(currentDetail.status)" size="small">
              {{ getStatusText(currentDetail.status) }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>

        <!-- 时间信息 -->
        <el-descriptions title="时间信息" :column="2" border size="default" style="margin-top: 20px">
          <el-descriptions-item label="创建时间">
            {{ currentDetail.created_at }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间">
            {{ currentDetail.updated_at }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleEditFromDetail">
            <el-icon><Edit /></el-icon>
            编辑配置
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search, Refresh, Plus, Edit, Delete, View, ArrowUp, ArrowDown
} from '@element-plus/icons-vue'
import ConfigEditDialog from './ConfigEditDialog.vue'
import DialogHeader from '@/components/DialogHeader.vue'
import api from '@/utils/api'
import { createLogger } from '@/utils/logger'

const componentLogger = createLogger('ConfigManagement')
const emit = defineEmits(['stats-updated'])

const loading = ref(false)
const configs = ref([])
const clusterTags = ref([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const paginationVisible = ref(false)
const advancedSearchExpanded = ref(false)

const searchForm = reactive({
  cluster_tag: '',
  config_name: '',
  is_monitor: '',
  is_alert: '',
  status: ''
})

const dialogVisible = ref(false)
const currentConfig = ref(null)
const isEdit = ref(false)

const detailDialogVisible = ref(false)
const currentDetail = ref(null)

// 状态映射
const statusMap = {
  'running': { text: '仅监控', type: 'primary' },
  'stopped': { text: '已停止', type: 'info' },
  'enAlert': { text: '启用告警', type: 'success' },
  'disAlert': { text: '禁用告警', type: 'warning' },
  'enAll': { text: '全部启用', type: 'success' },
  'disAll': { text: '全部禁用', type: 'danger' }
}

const getStatusText = (status) => {
  return statusMap[status]?.text || status
}

const getStatusType = (status) => {
  return statusMap[status]?.type || 'info'
}

const getClusterTagType = (tag) => {
  const types = ['primary', 'success', 'warning', 'danger', 'info']
  const index = tag.charCodeAt(0) % types.length
  return types[index]
}

const getBeNodesCount = (beNodes) => {
  if (!beNodes) return 0
  return beNodes.split(',').filter(n => n.trim()).length
}

// 计算FE从节点数量
const getFeSlaveNodesCount = (feSlaveNodes) => {
  if (!feSlaveNodes) return '无'
  const count = feSlaveNodes.split(',').filter(n => n.trim()).length
  return count > 0 ? `${count}个节点` : '无'
}

// 获取配置列表
const fetchConfigs = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      ...searchForm
    }
    
    // 过滤空值
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null) {
        delete params[key]
      }
    })
    
    const response = await api.get('/starrocks-cluster-monitor/configs', { params })
    if (response.data.success) {
      configs.value = response.data.data.rows
      total.value = response.data.data.total
      componentLogger.info('配置列表加载成功', { total: total.value })
    }
  } catch (error) {
    componentLogger.error('加载配置列表失败', error)
    ElMessage.error('加载配置列表失败')
  } finally {
    loading.value = false
  }
}

// 获取集群标识列表
const fetchClusterTags = async () => {
  try {
    const response = await api.get('/starrocks-cluster-monitor/configs/cluster-tags')
    if (response.data.success) {
      clusterTags.value = response.data.data
    }
  } catch (error) {
    componentLogger.error('加载集群标识列表失败', error)
  }
}

const handleSearch = () => {
  currentPage.value = 1
  fetchConfigs()
}

const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  currentPage.value = 1
  fetchConfigs()
}

const handleRefresh = () => {
  fetchConfigs()
  fetchClusterTags()
  emit('stats-updated')
  ElMessage.success('刷新成功')
}

const togglePagination = () => {
  paginationVisible.value = !paginationVisible.value
}

const handleCreate = () => {
  currentConfig.value = null
  isEdit.value = false
  dialogVisible.value = true
}

const handleEdit = async (row) => {
  try {
    loading.value = true
    componentLogger.info('编辑配置 - 请求配置', { id: row.id })
    
    // 获取完整的配置详情
    const response = await api.get(`/starrocks-cluster-monitor/configs/${row.id}`)
    
    componentLogger.info('编辑配置 - API响应', {
      success: response.data.success,
      hasData: !!response.data.data,
      prometheus_url: response.data.data?.prometheus_url,
      fe_query: response.data.data?.fe_query,
      be_query: response.data.data?.be_query,
      enable_prometheus: response.data.data?.enable_prometheus
    })
    
    if (response.data.success) {
      currentConfig.value = response.data.data
      isEdit.value = true
      dialogVisible.value = true
      
      componentLogger.info('编辑配置 - currentConfig设置完成', {
        prometheus_url: currentConfig.value?.prometheus_url,
        fe_query: currentConfig.value?.fe_query,
        be_query: currentConfig.value?.be_query
      })
    } else {
      ElMessage.error('获取配置详情失败')
    }
  } catch (error) {
    componentLogger.error('获取配置详情失败', error)
    ElMessage.error('获取配置详情失败')
  } finally {
    loading.value = false
  }
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除配置"${row.config_name}"吗？此操作不可恢复。`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await api.delete(`/starrocks-cluster-monitor/configs/${row.id}`)
    if (response.data.success) {
      ElMessage.success('删除成功')
      fetchConfigs()
      emit('stats-updated')
    }
  } catch (error) {
    if (error !== 'cancel') {
      componentLogger.error('删除配置失败', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleDialogSuccess = () => {
  fetchConfigs()
  fetchClusterTags()
  emit('stats-updated')
}

const handleSizeChange = () => {
  currentPage.value = 1
  fetchConfigs()
}

const handlePageChange = () => {
  fetchConfigs()
}

// 查看详情
const handleViewDetail = async (row) => {
  try {
    loading.value = true
    componentLogger.info('查看详情 - 请求配置', { id: row.id })
    
    // 获取完整的配置详情
    const response = await api.get(`/starrocks-cluster-monitor/configs/${row.id}`)
    
    componentLogger.info('查看详情 - API响应', {
      success: response.data.success,
      hasData: !!response.data.data,
      prometheus_url: response.data.data?.prometheus_url,
      fe_query: response.data.data?.fe_query,
      be_query: response.data.data?.be_query
    })
    
    if (response.data.success) {
      currentDetail.value = response.data.data
      detailDialogVisible.value = true
      
      componentLogger.info('查看详情 - currentDetail设置完成', {
        prometheus_url: currentDetail.value?.prometheus_url,
        fe_query: currentDetail.value?.fe_query,
        be_query: currentDetail.value?.be_query
      })
    } else {
      ElMessage.error('获取配置详情失败')
    }
  } catch (error) {
    componentLogger.error('获取配置详情失败', error)
    ElMessage.error('获取配置详情失败')
  } finally {
    loading.value = false
  }
}

// 从详情进入编辑
const handleEditFromDetail = () => {
  detailDialogVisible.value = false
  currentConfig.value = { ...currentDetail.value }
  isEdit.value = true
  dialogVisible.value = true
}

// 切换监控开关
const handleToggleMonitor = async (row, newValue) => {
  const oldValue = row.is_monitor
  
  // 设置loading状态
  row._monitorLoading = true
  
  try {
    componentLogger.info('Toggle monitor BEFORE API call', {
      id: row.id,
      is_monitor: row.is_monitor,
      is_alert: row.is_alert,
      is_restart: row.is_restart,
      status: row.status,
      oldValue,
      newValue
    })
    
    const response = await api.put(`/starrocks-cluster-monitor/configs/${row.id}`, {
      is_monitor: newValue
    })
    
    componentLogger.info('Toggle monitor API response', {
      success: response.data.success,
      data: response.data.data
    })
    
    if (response.data.success && response.data.data) {
      // 使用后端返回的完整数据更新所有字段，确保前后端状态一致
      const updatedData = response.data.data
      row.is_monitor = updatedData.is_monitor
      row.is_alert = updatedData.is_alert
      row.is_restart = updatedData.is_restart
      row.status = updatedData.status
      
      componentLogger.info('Toggle monitor AFTER update', {
        id: row.id,
        is_monitor: row.is_monitor,
        is_alert: row.is_alert,
        is_restart: row.is_restart,
        status: row.status
      })
      
      ElMessage.success(`${newValue === 1 ? '已开启' : '已关闭'}监控`)
      emit('stats-updated')
    } else {
      ElMessage.error(response.data.message || '操作失败')
    }
  } catch (error) {
    componentLogger.error('切换监控开关失败', error)
    ElMessage.error('操作失败')
  } finally {
    row._monitorLoading = false
  }
}

// 切换告警开关
const handleToggleAlert = async (row, newValue) => {
  // 如果监控未开启，不允许开启告警（虽然UI上已经disabled了，但双重保护）
  if (row.is_monitor === 0) {
    ElMessage.warning('请先开启监控')
    return
  }
  
  const oldValue = row.is_alert
  
  // 设置loading状态
  row._alertLoading = true
  
  try {
    componentLogger.info('Toggle alert BEFORE API call', {
      id: row.id,
      is_monitor: row.is_monitor,
      is_alert: row.is_alert,
      is_restart: row.is_restart,
      status: row.status,
      oldValue,
      newValue
    })
    
    const response = await api.put(`/starrocks-cluster-monitor/configs/${row.id}`, {
      is_alert: newValue
    })
    
    componentLogger.info('Toggle alert API response', {
      success: response.data.success,
      data: response.data.data
    })
    
    if (response.data.success && response.data.data) {
      // 使用后端返回的完整数据更新所有字段，确保前后端状态一致
      const updatedData = response.data.data
      row.is_monitor = updatedData.is_monitor
      row.is_alert = updatedData.is_alert
      row.is_restart = updatedData.is_restart
      row.status = updatedData.status
      
      componentLogger.info('Toggle alert AFTER update', {
        id: row.id,
        is_monitor: row.is_monitor,
        is_alert: row.is_alert,
        is_restart: row.is_restart,
        status: row.status
      })
      
      ElMessage.success(`${newValue === 1 ? '已开启' : '已关闭'}告警`)
      emit('stats-updated')
    } else {
      ElMessage.error(response.data.message || '操作失败')
    }
  } catch (error) {
    componentLogger.error('切换告警开关失败', error)
    ElMessage.error('操作失败')
  } finally {
    row._alertLoading = false
  }
}

// 切换自动重启开关
const handleToggleRestart = async (row, newValue) => {
  // 如果监控未开启，不允许开启自动重启（虽然UI上已经disabled了，但双重保护）
  if (row.is_monitor === 0) {
    ElMessage.warning('请先开启监控')
    return
  }
  
  const oldValue = row.is_restart
  
  // 设置loading状态
  row._restartLoading = true
  
  try {
    componentLogger.info('Toggle restart BEFORE API call', {
      id: row.id,
      is_monitor: row.is_monitor,
      is_alert: row.is_alert,
      is_restart: row.is_restart,
      status: row.status,
      oldValue,
      newValue
    })
    
    const response = await api.put(`/starrocks-cluster-monitor/configs/${row.id}`, {
      is_restart: newValue
    })
    
    componentLogger.info('Toggle restart API response', {
      success: response.data.success,
      data: response.data.data,
      message: response.data.message
    })
    
    if (response.data.success && response.data.data) {
      // 使用后端返回的完整数据更新所有字段，确保前后端状态一致
      const updatedData = response.data.data
      row.is_monitor = updatedData.is_monitor
      row.is_alert = updatedData.is_alert
      row.is_restart = updatedData.is_restart
      row.status = updatedData.status
      
      componentLogger.info('Toggle restart AFTER update', {
        id: row.id,
        is_monitor: row.is_monitor,
        is_alert: row.is_alert,
        is_restart: row.is_restart,
        status: row.status
      })
      
      ElMessage.success(`${newValue === 1 ? '已开启' : '已关闭'}自动重启`)
      emit('stats-updated')
    } else {
      ElMessage.error(response.data.message || '操作失败')
    }
  } catch (error) {
    componentLogger.error('切换自动重启开关失败', error)
    ElMessage.error('操作失败')
  } finally {
    row._restartLoading = false
  }
}

onMounted(() => {
  fetchConfigs()
  fetchClusterTags()
})

defineExpose({
  fetchData: fetchConfigs
})
</script>

<style scoped>
.config-management {
  margin-top: 20px;
}

.search-section {
  margin-bottom: 20px;
}

.search-card {
  border-radius: 8px;
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.search-title .el-icon {
  color: #409eff;
}

.search-form-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 20px;
}

.search-form-fields {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.search-form-fields .el-form-item {
  margin-bottom: 0;
}

.search-form-actions {
  display: flex;
  gap: 12px;
  flex-shrink: 0;
}

.table-container {
  min-height: 600px;
}

.enhanced-table {
  font-family: 'Inter', 'PingFang SC', 'Microsoft YaHei', sans-serif;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
}

.table-container .el-table {
  width: 100% !important;
  border-radius: 16px;
  overflow: hidden;
  background: #fff;
}

.table-container .el-table__header {
  background: #f8f9fa;
  border-bottom: 1px solid #e4e7ed;
}

.table-container .el-table th {
  background: transparent !important;
  border: none !important;
  padding: 16px 12px !important;
  font-weight: 500 !important;
  color: #606266 !important;
  font-size: 14px !important;
}

.enhanced-table .el-table__header-wrapper th {
  font-size: 14px !important;
  font-weight: 500 !important;
  color: #606266 !important;
  white-space: nowrap !important;
}

.enhanced-table :deep(.el-table__header-wrapper) th .cell {
  white-space: nowrap !important;
  overflow: visible !important;
  display: flex !important;
  align-items: center !important;
  flex-wrap: nowrap !important;
}

/* 排序图标容器不换行 */
.enhanced-table :deep(.el-table__header-wrapper) th .caret-wrapper {
  flex-shrink: 0 !important;
  margin-left: 4px !important;
}

/* 表格内容字体大小统一 */
.enhanced-table .el-table__body-wrapper td {
  font-size: 14px !important;
}

.table-container .el-table td {
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  padding: 12px;
  font-size: 14px;
  font-weight: 400;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
}

.enhanced-table :deep(.el-table__header th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.action-buttons .el-button {
  width: 32px;
  height: 32px;
  padding: 0;
}

/* 分页区域 */
.pagination-section {
  padding: 16px;
  border-top: 1px solid #f0f0f0;
  background: #fafafa;
}

.pagination-section .el-pagination {
  display: flex;
  justify-content: center;
}

/* 分页折叠动画 */
.pagination-slide-enter-active,
.pagination-slide-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.pagination-slide-enter-from,
.pagination-slide-leave-to {
  opacity: 0;
  max-height: 0;
  overflow: hidden;
}

.pagination-slide-enter-to,
.pagination-slide-leave-from {
  opacity: 1;
  max-height: 200px;
}

.enhanced-pagination {
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  padding: 16px 24px;
  box-shadow: 
    0 8px 32px rgba(0, 0, 0, 0.08),
    0 2px 8px rgba(0, 0, 0, 0.04),
    inset 0 1px 0 rgba(255, 255, 255, 0.9);
  border: 1px solid rgba(255, 255, 255, 0.2);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.enhanced-pagination:hover {
  transform: translateY(-2px);
  box-shadow: 
    0 12px 40px rgba(0, 0, 0, 0.12),
    0 4px 16px rgba(0, 0, 0, 0.06),
    inset 0 1px 0 rgba(255, 255, 255, 0.95);
}

.enhanced-pagination .el-pagination__total {
  color: #4a5568;
  font-weight: 600;
  font-size: 14px;
  letter-spacing: 0.5px;
}

.enhanced-pagination .el-pagination__sizes .el-select .el-input__inner {
  border-radius: 8px;
  border: 1px solid rgba(220, 223, 230, 0.8);
  background: rgba(255, 255, 255, 0.9);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  font-weight: 500;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.02);
}

.enhanced-pagination .el-pagination__sizes .el-select .el-input__inner:hover {
  border-color: rgba(64, 158, 255, 0.6);
  background: #fff;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.1);
}

.enhanced-pagination .el-pagination__sizes .el-select .el-input__inner:focus {
  border-color: #409eff;
  background: #fff;
  box-shadow: 
    0 0 0 3px rgba(64, 158, 255, 0.1),
    0 4px 12px rgba(64, 158, 255, 0.15);
}

.enhanced-pagination .btn-prev,
.enhanced-pagination .btn-next {
  border-radius: 8px;
  border: 1px solid rgba(220, 223, 230, 0.8);
  background: linear-gradient(135deg, #fff 0%, #fafbfc 100%);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  font-weight: 600;
  color: #4a5568;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.02);
  min-width: 40px;
  height: 40px;
}

.enhanced-pagination .btn-prev:hover,
.enhanced-pagination .btn-next:hover {
  background: linear-gradient(135deg, #409eff 0%, #66b3ff 100%);
  border-color: transparent;
  color: white;
  transform: translateY(-2px);
  box-shadow: 
    0 8px 25px rgba(64, 158, 255, 0.25),
    0 3px 10px rgba(64, 158, 255, 0.15);
}

.enhanced-pagination .btn-prev:active,
.enhanced-pagination .btn-next:active {
  transform: translateY(0);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
}

.enhanced-pagination .el-pager li {
  border-radius: 8px;
  border: 1px solid rgba(220, 223, 230, 0.8);
  background: linear-gradient(135deg, #fff 0%, #fafbfc 100%);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  font-weight: 600;
  margin: 0 3px;
  min-width: 40px;
  height: 40px;
  color: #4a5568;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.02);
}

.enhanced-pagination .el-pager li:hover {
  background: linear-gradient(135deg, #f0f7ff 0%, #e6f3ff 100%);
  border-color: rgba(64, 158, 255, 0.3);
  color: #409eff;
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(64, 158, 255, 0.15);
}

.enhanced-pagination .el-pager li.is-active {
  background: linear-gradient(135deg, #409eff 0%, #66b3ff 100%);
  border-color: transparent;
  color: white;
  box-shadow: 
    0 8px 25px rgba(64, 158, 255, 0.3),
    0 3px 10px rgba(64, 158, 255, 0.2);
  transform: translateY(-1px);
}

.enhanced-pagination .el-pager li:active {
  transform: translateY(0);
}

.enhanced-pagination .el-pagination__jump {
  color: #4a5568;
  font-weight: 600;
}

.enhanced-pagination .el-pagination__jump .el-input__inner {
  border-radius: 8px;
  border: 1px solid rgba(220, 223, 230, 0.8);
  background: rgba(255, 255, 255, 0.9);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  font-weight: 500;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.02);
  height: 40px;
}

.enhanced-pagination .el-pagination__jump .el-input__inner:hover {
  border-color: rgba(64, 158, 255, 0.6);
  background: #fff;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.1);
}

.enhanced-pagination .el-pagination__jump .el-input__inner:focus {
  border-color: #409eff;
  background: #fff;
  box-shadow: 
    0 0 0 3px rgba(64, 158, 255, 0.1),
    0 4px 12px rgba(64, 158, 255, 0.15);
}

/* 表格头部样式 */
.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.table-title .el-icon {
  color: #409eff;
}

.table-header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.table-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.refresh-btn {
  border-radius: 6px;
  font-weight: 500;
}

.page-count {
  color: #606266;
  font-size: 14px;
  font-weight: 500;
}

.divider {
  width: 1px;
  height: 16px;
  background: #e4e7ed;
  margin: 0 8px;
}

.table-header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.table-info {
  display: flex;
  align-items: center;
}

.refresh-btn {
  background: linear-gradient(135deg, #67C23A 0%, #85CE61 100%);
  border: none;
  border-radius: 8px;
  color: #fff;
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  font-weight: 500;
}

.refresh-btn:hover {
  background: linear-gradient(135deg, #85CE61 0%, #67C23A 100%);
  box-shadow: 0 6px 20px rgba(103, 194, 58, 0.4);
  transform: translateY(-2px);
  color: #fff;
}

.pagination-control-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 8px;
  background: rgba(64, 158, 255, 0.08);
  border: 1px solid rgba(64, 158, 255, 0.2);
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  user-select: none;
  font-size: 12px;
  height: 24px;
}

.pagination-control-wrapper:hover {
  background: rgba(64, 158, 255, 0.12);
  border-color: rgba(64, 158, 255, 0.3);
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
}

.page-count {
  font-size: 12px;
  font-weight: 500;
  color: #909399;
  line-height: 1;
}

.divider {
  width: 1px;
  height: 12px;
  background: rgba(64, 158, 255, 0.3);
  margin: 0 2px;
}

.pagination-info {
  font-size: 12px;
  font-weight: 500;
  color: #409eff;
  letter-spacing: 0.5px;
  min-width: 24px;
  text-align: center;
  line-height: 1;
}

.pagination-toggle-icon {
  font-size: 12px;
  color: #409eff;
  transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

/* 高级筛选样式 */
.advanced-filter-section {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #e4e7ed;
}

.advanced-filter-fields {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.advanced-filter-fields .el-form-item {
  margin-bottom: 0;
}

/* 高级筛选折叠动画 */
.advanced-filter-enter-active,
.advanced-filter-leave-active {
  transition: all 0.3s ease;
  max-height: 200px;
  overflow: hidden;
}

.advanced-filter-enter-from,
.advanced-filter-leave-to {
  opacity: 0;
  max-height: 0;
  margin-top: 0;
  padding-top: 0;
}

.advanced-filter-enter-to,
.advanced-filter-leave-from {
  opacity: 1;
  max-height: 200px;
  margin-top: 16px;
  padding-top: 16px;
}
</style>

